package com.exm.collectcodenew.activemq.consumer;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

public class ActiveMQTopicMsListenerConsumer {
    public static final String ACTIVEMQ_URL ="tcp://59.110.35.177:61616";
    public static final String TOPIC_NAME="topic01";

    public static void main(String[] args) throws JMSException, IOException {
        //1.连接工厂，按照给定的url地址，采用默认用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂，获取连接connection并启动访问
        Connection connection =activeMQConnectionFactory.createConnection();
        connection.start();
        //3.创建会话session
        //两个参数，第一个叫事务/第二个叫签收
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        //4.创建目的地（具体是队列还是主题topic）
        Topic topic =session.createTopic(TOPIC_NAME);
        //5.创建消费者
        MessageConsumer messageConsumer= session.createConsumer(topic);
        //6.消费者创建监听
        messageConsumer.setMessageListener((message)->{
            if(message!=null && message instanceof  TextMessage){
                TextMessage textMessage = (TextMessage)message;
                try {
                    System.out.println("消息消费为："+textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        System.in.read();//接受键盘输入，按下Enter键结束输入，保持控制台不灭
        messageConsumer.close();
        session.close();
        connection.close();
        System.out.println("****消息消费完成****");
    }
}
